<?php

namespace app\admin\controller\issuer;
use app\common\controller\Backend;
use think\Db;
use think\Loader;

/**
 * 用户管理
 *
 * @icon fa fa-file-text-o
 */
class Distributor extends Backend
{
    /**
     * School模型对象
     */
    protected $searchFields = '';
    protected $model = null;
    protected $noNeedRight = ['getProvinceCity'];
    protected $isSuperAdmin = false;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\issuer\Distributor();
        //是否超级管理员
        $this->isSuperAdmin = $this->auth->isSuperAdmin();
    }

    /**
      * 渠道管理
     */
    public function index()
    {
        $request = $this->request->request();
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where_new =[];
            $year = isset($request['year'])?$request['year']:'';
            $distributor_type = isset($request['distributor_type'])?$request['distributor_type']:'';
            $distributor = isset($request['distributor'])?$request['distributor']:'';
            $audit_status = isset($request['audit_status'])?$request['audit_status']:'全部';
            $province = isset($request['province'])?$request['province']:'全国';
            $city = isset($request['city'])?$request['city']:'全部';
            if ($year) $where_new['year'] = $year;
            if ($distributor) $where_new['distributor_name'] = $distributor;
            if ($distributor_type) $where_new['distributor_type'] = $distributor_type;
            if ($audit_status != '全部') $where_new['audit_status'] = $audit_status;
            if ($province != '全国') $where_new['province'] = $province;
            if ($city != '全部') $where_new['city'] = $city;
             if($this->auth->id > 1){
                $where_new['creater_id'] = $this->auth->id;
            }
            $where_new['province_id'] = ['>',0];
            $total = $this->model
                ->where($where)
                ->where($where_new)
                ->order($sort, $order)
                ->count();
            $list =  $this->model
                ->where($where_new)
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);
            foreach ($list as $w=>&$v){
                $v['new_address'] = $v['province'].'-'.$v['city'];
                $v['price'] = $v['price']/100;
                $card_put_info = Db::name('card_put_info')
                    ->where(['audit_status'=>['in',[1,3,4]],'distributor_id'=>$v['id'],'put_type'=>0])
                    ->field('sum(put_price*put_num) as total_price')->find();
             //   var_dump($card_put_info);
              //  $num = Db::name('card_log')->where(['card_type'=>0,'distributor_id'=>$v['id']])->count('id');
                $v['activate_num'] = Db::name('card_log')->where(['is_activate'=>1,'distributor_id'=>$v['id']])->count('id');
                $v['put_amount'] = $card_put_info['total_price']/100;
            }

            return json($result);
        }

        $this->assign('province', get_pro());
        $this->assign('city', []);
        return $this->view->fetch();
    }

    /**
     * 渠道创建
     */
    public function add(){
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            $where['distributor_name'] = $params['distributor_name'];
            $dis_info = $this->model->where($where)->find();
            if($dis_info){
                $this->error('该渠道名称已存在');
            }
            if(preg_match('/^0?(13|14|15|17|18)[0-9]{9}$/',$params['username']) == false){
                $this ->error('手机号格式不正确，请重新输入');
            }
            if($params['price'] < 3){
                $this ->error('最低不能低于3元');
            }
            $params['price'] = 100*$params['price'];
            $province_city = Db::name('province_city')->where(['id'=>$params['city_id']])->find();
            $params['province']=$province_city['province'];
            $params['city']=$province_city['city'];
            $params['province_id']=$province_city['province_id'];
            $params['city_id']=$province_city['id'];
            $params['createtime'] = time();
            $params['updatetime'] = time();
            $params['creater_id'] = session('admin.id');
            $params['avatar'] = '/www/gkzzd/uploads/20201113/760f593790f35994a77c03fd7dfe9f74.png';
            $res = $this->model->insert($params);
            if ($res){
                $this->success();
            }
            $this->error();
        }

        return $this->view->fetch();
    }

    /**
     * 发行
     */
    public function issue($ids = null){
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            $province_city = Db::name('province_city')->where(['id'=>$params['city_id']])->find();
            $params['province']=$province_city['province'];
            $params['city']=$province_city['city'];
            $params['province_id']=$province_city['province_id'];
            $params['city_id']=$province_city['id'];
            $row = $this->model->get($params['distributor_id']);
            if (!$row) {
                $this->error(__('No Results were found'));
            }
            if($params['year'] < $row['year']){
                $this->error('发卡年份不能低于'.$row['year']);
            }
            $params['put_price'] = isset($params['put_price'])&&$params['put_price']!=''?100*$params['put_price']:'';
            if($params['put_type'] ==0 && $row['price'] > $params['put_price']){
               $this->error('发行单价过低，最低发行单价为：'.$row['price']/100);
            }
            if($params['put_num']<=0){
                $this->error('发行张数不能小于0');
            }
            $params['create_time'] = time();
            $params['update_time'] = time();
            $params['admin_id'] = session('admin.id');
            $res = Db::name('card_put_info')->insert($params);
            if ($res){
                $this->success();
            }
            $this->error();
        }

        $this->view->assign('ids', $ids);
        return $this->view->fetch();

    }

    public function getProvinceCity(){
        $re=Db::name('province_city')
            ->field('province,province_id,city,id as city_id')
            ->cache(3000)
            ->select();
        $province_arr=[];
        foreach($re as $vo){
            if(!key_exists($vo['province_id'],$province_arr)){
                $province_arr[$vo['province_id']]=$vo['province'];
            }
        }
        $arr=[];
        foreach ($province_arr as $k=>$v){
            $value=$k;
            $label=$v;
            $children=[];
            foreach($re as $voo){
                if($k == $voo['province_id']){
                    array_push($children,['value'=>$voo['city_id'],'label'=>$voo['city']]);
                }
            }
            array_push($arr,['value'=>$value,'label'=>$label,'children'=>$children]);
        }
        $data = [
            'info'=>json_encode($arr,JSON_UNESCAPED_UNICODE )
        ];

        $this->success('请求成功','',$data);
    }


    /**
     * 审核
     * @return string|\think\response\Json
     */
    public function audit($ids=null){  //审核
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign("row", $row);
        $this->view->assign("sh_id", $ids);
        return $this->view->fetch();
    }
    /**
     * 审核
     * @return string|\think\response\Json
     */
    public function account_audit(){  //审核
        $sh_id = $this->request->request("sh_id");
        $row = $this->model->get($sh_id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $sh_id = $this->request->request("sh_id");
            $status = $this->request->request("status");
            if ($sh_id) {
                try {
                    $update['audit_status'] = $status;
                    $update['updatetime'] = time();
                    // $where['id'] = $sh_id;
//                    $params['update_time'] = time();
//                    $params['admin_id'] = $this->auth->id;
//                    Db::name('province_city_region')->where(['city_id'=>$ids])->update(['city'=>$params['city'],'update_time'=>time()]);
                    $result = $this->model->where(['id'=>$sh_id])->update($update);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();

    }

    /**
     * 关闭
     * @return string|\think\response\Json
     */
    public function close($ids=null){  //审核
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $update['status'] = 'hidden';
        $update['updatetime'] = time();
        $result = $this->model->where(['id'=>$ids])->update($update);
        if($result){
            $this->success();
        }
        $this->error();
    }
    /**
     * open
     * @return string|\think\response\Json
     */
    public function open($ids=null){  //审核
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $update['status'] = 'normal';
        $update['updatetime'] = time();
        $result = $this->model->where(['id'=>$ids])->update($update);
        if($result){
            $this->success();
        }
        $this->error();
    }


    public function edit($ids = NULL){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
//                    $params['update_time'] = time();
//                    $params['admin_id'] = $this->auth->id;
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
